package com.petsbang.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import com.petsbang.http.NetHelper;
import com.petsbang.vo.PictureInfo;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class AsyncImageLoader {
	private static final String TAG = "AsyncImageLoader";

	private HashMap<String, SoftReference<Bitmap>> imageCache;
	private BlockingQueue<Runnable> queue;
	private ThreadPoolExecutor executor;

	public AsyncImageLoader() {
		imageCache = new HashMap<String, SoftReference<Bitmap>>();

		// 线程池：最大50条，每次执行：1条，空闲线程结束的超时时间：180秒
		queue = new LinkedBlockingQueue<Runnable>();
		executor = new ThreadPoolExecutor(1, 50, 180, TimeUnit.SECONDS, queue);
	}

	public Bitmap loadDrawable(final Context context, final String imageUrl,
			final ImageCallback imageCallback) {
		// 如果Cache里有图片Url
		if (imageCache.containsKey(imageUrl)) {
			SoftReference<Bitmap> softReference = imageCache.get(imageUrl);
			Bitmap drawable = softReference.get();
			if (drawable != null) {
				return drawable;
			}
		}
		final Handler handler = new Handler() {
			public void handleMessage(Message message) {
				imageCallback.imageLoaded((Bitmap) message.obj, imageUrl);
			}
		};

		// 用线程池来做下载图片的任务
		executor.execute(new Runnable() {
			@Override
			public void run() {
				Bitmap drawable = loadImageFromUrl(context, imageUrl);
				imageCache.put(imageUrl, new SoftReference<Bitmap>(drawable));
				Message message = handler.obtainMessage(0, drawable);
				handler.sendMessage(message);
			}
		});

		return null;
	}

	/*
	 * 网络图片先下载到本地cache目录保存，以imagUrl的图片文件名保存。如果有同名文件在cache目录就从本地加载
	 */
	public static Bitmap loadImageFromUrl(Context context, String imageUrl) {

		if (imageUrl == null) {
			return null;
		}
		
		Bitmap bm = null;
		try {
			bm = FileTools.readPicFile(imageUrl);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		if (bm == null) {
			bm = NetHelper.getImageBitmap(imageUrl);
			try {
				FileTools.savePicFile(bm, imageUrl);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		return bm;
	}

	/*
	 * 回调接口
	 */
	public interface ImageCallback {
		public void imageLoaded(Bitmap imageDrawable, String imageUrl);
	}

	String showUrl01;
	String showUrl02;
	String showUrl03;

	public void setShowIndex(String showUrl01, String showUrl02,
			String showUrl03,ArrayList<PictureInfo> picList) {
		this.showUrl01 = showUrl01;
		this.showUrl02 = showUrl02;
		this.showUrl03 = showUrl03;
		
		int size = picList.size();
		for (int i = 0; i <size; i++) {
			String tmpUrl = picList.get(i).getLarge_url();
			if (tmpUrl.equals(showUrl01) || tmpUrl.equals(showUrl02) || tmpUrl.equals(showUrl03) ) {
				continue;
			}
			
			if (imageCache.containsKey(tmpUrl)) {
				SoftReference<Bitmap> softReference = imageCache.get(tmpUrl);
				Bitmap drawable = softReference.get();
				if (drawable != null) {
					drawable.recycle();
				}
				
				imageCache.remove(tmpUrl);
			}
			
		}
		
		System.gc();
	}

}
